package admin

import (
	"fmt"
	"go-weiqi-system/config"
	"go-weiqi-system/internal/utils"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type UploadController struct {
	Config *config.Config
}

// Upload 文件上传
func (ctrl *UploadController) Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		utils.Error(c, "请选择文件")
		return
	}

	// 检查文件大小
	if file.Size > ctrl.Config.MaxUploadSize {
		utils.Error(c, "文件大小超过限制")
		return
	}

	// 检查文件类型
	ext := strings.ToLower(filepath.Ext(file.Filename))
	allowedExts := []string{".jpg", ".jpeg", ".png", ".gif", ".webp", ".pdf", ".doc", ".docx"}
	allowed := false
	for _, allowedExt := range allowedExts {
		if ext == allowedExt {
			allowed = true
			break
		}
	}
	if !allowed {
		utils.Error(c, "不支持的文件类型")
		return
	}

	// 生成文件名
	timestamp := time.Now().Unix()
	filename := fmt.Sprintf("%d%s", timestamp, ext)

	// 创建上传目录（按日期分类）
	dateDir := time.Now().Format("20060102")
	uploadPath := filepath.Join(ctrl.Config.UploadPath, dateDir)
	if err := os.MkdirAll(uploadPath, 0755); err != nil {
		utils.Error(c, "创建目录失败")
		return
	}

	// 保存文件
	savePath := filepath.Join(uploadPath, filename)
	if err := c.SaveUploadedFile(file, savePath); err != nil {
		utils.Error(c, "保存文件失败")
		return
	}

	// 返回文件URL
	fileURL := fmt.Sprintf("/uploads/%s/%s", dateDir, filename)
	utils.Success(c, gin.H{
		"url":      fileURL,
		"filename": file.Filename,
		"size":     file.Size,
	}, "上传成功")
}
